<?php

namespace app\opengzh\service;
use app\common\logic\CommonLogic;
use app\common\model\Article;
use app\common\model\GzhAccount;

use app\common\model\GzhLog;
use app\common\model\GzhMedia;
use app\common\model\GzhTitle;
use app\common\model\Swiper;
use app\opengzh\logic\ToolLogic;

use GuzzleHttp\Client;
use think\facade\Cache;
use think\facade\Db;

class OpenPlatformService  {

    //发布文章
    public function freepublish($appid,$title_info){
        $token = $this->getAuthorizerAccessToken($appid);
        $url = 'https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token='.$token;

        $client = new Client([
            'timeout'  => 6.0,
        ]);
        $response = $client->post($url,[
            'json'=>[
                'media_id'=>$title_info['media_id']
            ]
        ]);
        $commonLogic = new CommonLogic();
        $longtitle = $commonLogic->getLongTitle($title_info['title'],$title_info['keyword']);
        $str = $response -> getBody()->getContents();
        $arr = json_decode($str,true);
        $logModel = new GzhLog();
        if($arr['errcode']==0){
            $logModel->insert([
                'appid'=>$appid,
                'desc'=>'发布文章成功：'.$longtitle,
                'extra'=>$str,
                'type'=>7,
                'result'=>1,
                'created_at'=>time(),
            ]);
            $titleModel = new GzhTitle();
            $titleModel->where('id',$title_info['id'])->save([
                'is_pub'=>2,
                'pub_time'=>time(),
                'pub_day'=>date('Y-m-d',time()),
            ]);
            return [
                'status'=>true,
            ];
        }else{
            $res = $logModel->where('appid',$appid)
                ->where('type',7)
                ->where('desc','发布文章失败：'.$longtitle)
                ->where('result',2)
                ->findOrEmpty();
            if(!$res->isEmpty()){
                $titleModel = new GzhTitle();
                $titleModel->where('id',$title_info['id'])->delete();
                $logModel->insert([
                    'appid'=>$appid,
                    'desc'=>'文章发布错误删除中：'.$longtitle.'_id:'.$title_info['id'],
                    'extra'=>$str,
                    'type'=>8,
                    'result'=>1,
                    'created_at'=>time(),
                ]);
            }else{
                $logModel->insert([
                    'appid'=>$appid,
                    'desc'=>'发布文章失败：'.$longtitle.'token:'.$token,
                    'extra'=>$str,
                    'type'=>7,
                    'result'=>2,
                    'created_at'=>time(),
                ]);
            }

            return [
                'status'=>false,
            ];
        }
    }
    public function draft($appid,$content,$title_info=[]){
        $token = $this->getAuthorizerAccessToken($appid);
        $url = 'https://api.weixin.qq.com/cgi-bin/draft/add?access_token='.$token;
        //图文消息内的图片

        $swiperModel = new Swiper();
        $path = $swiperModel->where('id',8)->value('path');
        $media_res = $this->uploadImage($appid,$path);
        if(!$media_res['status']){
            var_dump('获取永久素材失败');
            return ;
        }
        $thumb_media_id = $media_res['media_id'];

        $gamecontent1 = '<p style="margin-bottom: 0px;text-align: center;">👇👇👇点击进入游戏👇👇👇</p ><section>
                <mp-common-miniprogram 
                    data-miniprogram-nickname="致命火线之佣兵传奇" 
                    data-miniprogram-avatar="http://mmbiz.qpic.cn/mmbiz_png/F9mxyMqyaTL53njUibbC6icTjYobPXr3ichZnvhB9RFib3W4kibaOvyWVoMxsjmL7V4EJgzTjJUN2msLmWwZ8SQPjOw/640?wx_fmt=png&amp;wxfrom=200" 
                    data-miniprogram-title="最新传奇小程序版本来了！" 
                    data-miniprogram-imageurl="http://mmbiz.qpic.cn/mmbiz_jpg/3XFuQeKibbFVNuHyCfSCicbmO0NvA3aE9KH9cslvoeQWXUyeEMiaQr7pv0hEEYbDU5vzAgNk1MBbe3mxPdhrS0nzQ/0?wx_fmt=jpeg" 
                    data-miniprogram-type="card" 
                    data-miniprogram-servicetype="4" 
                    class="js_uneditable custom_select_card mp_miniprogram_iframe" 
                    data-miniprogram-appid="wxc2dc91f6b0a9b0d4" 
                    data-miniprogram-path="?cname=2863"></mp-common-miniprogram>
                    </section><p style="margin-bottom: 0px;text-align: center;">👆👆👆点击进入游戏<span style="letter-spacing: 0.578px;text-align: center;">👆👆👆</span></p >
                    <p style="margin-bottom: 0px;text-align: center;"><strong><span style="letter-spacing: 0.578px;text-align: center;"><br  /></span></strong></p ><p style="text-align: center;"><strong>👑内部特权礼包码：</strong></p ><p style="text-align: center;"><strong>vip666</strong></p ><p style="text-align: center;"><strong>vip888</strong></p ><p style="text-align: center;"><strong>vip999</strong></p ><p style="margin-bottom: 0px;text-align: center;"><span style="letter-spacing: 0.578px;text-align: center;"><br  /></span></p ><p style="display: none;"><mp-style-type data-value="10000"></mp-style-type></p >';


        $gamecontent2 = '<p style="margin-bottom: 0px;text-align: center;"><strong>🔥🔥🔥热门传奇小程序推荐🔥🔥🔥</strong></p >
                <p style="margin-bottom: 0px;text-align: center;">👇👇👇点击进入游戏👇👇👇</p ><section>
                <mp-common-miniprogram 
                    data-miniprogram-nickname="血饮天下" 
                    data-miniprogram-avatar="http://mmbiz.qpic.cn/sz_mmbiz_jpg/jK3eBT1DWQKsnsiaskZVXy0REiaaPibA6Wksgsyc257SjBtwCFIL5KPhOq1ibhqZuQ0Ar3PqMOPQtJ55kPtick2b4Nw/0?wx_fmt=jpeg" 
                    data-miniprogram-title="全新骷髅版本" 
                    data-miniprogram-imageurl="http://mmbiz.qpic.cn/sz_mmbiz_jpg/ZblWfPt1a19AJYVSpLYbeb7ibVHKrXuscatcm2I0lRu9yE0xl96BuCiap4BKlMkjaDLCvibddah90vP9icJCb1gtibQ/0?wx_fmt=jpeg" 
                    data-miniprogram-type="card" 
                    data-miniprogram-servicetype="4" 
                    class="js_uneditable custom_select_card mp_miniprogram_iframe" 
                    data-miniprogram-appid="wxd5fcf7bd53e2993d" 
                    data-miniprogram-path="?cname=2863"></mp-common-miniprogram>
                    </section><p style="margin-bottom: 0px;text-align: center;">👆👆👆点击进入游戏👆👆👆</p >';

        $gamecontent3 = '<p style="margin-bottom: 0px;text-align: center;">👇👇👇点击进入游戏👇👇👇</p ><section><section>
                <mp-common-miniprogram 
                    data-miniprogram-nickname="甜蜜冲刺" 
                    data-miniprogram-avatar="http://mmbiz.qpic.cn/sz_mmbiz_png/ZblWfPt1a19AJYVSpLYbeb7ibVHKrXuscpXfgGWA9coicZLmWwwo4cWRRPDUtGHU8Gqk5F94OYmsicOOribvicQ5Micw/0?wx_fmt=png" 
                    data-miniprogram-title="人气超变版！真良心传奇！" 
                    data-miniprogram-imageurl="http://mmbiz.qpic.cn/sz_mmbiz_jpg/ZblWfPt1a19AJYVSpLYbeb7ibVHKrXuscjn7PmSz7Ww0KQJIP5u0bjaLSNX9CKzQLqo2r5wmZRMET2YNhaVFrAg/0?wx_fmt=jpeg" 
                    data-miniprogram-type="card" 
                    data-miniprogram-servicetype="4" 
                    class="js_uneditable custom_select_card mp_miniprogram_iframe" 
                    data-miniprogram-appid="wx2892879fe9d12cff" 
                    data-miniprogram-path="?cname=2863"></mp-common-miniprogram>
                    </section><p style="margin-bottom: 0px;text-align: center;">👆👆👆点击进入游戏👆👆👆</p >';


        $gamecontent4 = '<p style="margin-bottom: 0px;text-align: center;">👇👇👇点击进入游戏👇👇👇</p ><section><section>
                <mp-common-miniprogram 
                    data-miniprogram-nickname="致命火线之佣兵传奇" 
                    data-miniprogram-avatar="http://mmbiz.qpic.cn/mmbiz_png/F9mxyMqyaTL53njUibbC6icTjYobPXr3ichZnvhB9RFib3W4kibaOvyWVoMxsjmL7V4EJgzTjJUN2msLmWwZ8SQPjOw/640?wx_fmt=png&amp;wxfrom=200" 
                    data-miniprogram-title="最新传奇小程序版本来了！" 
                    data-miniprogram-imageurl="http://mmbiz.qpic.cn/mmbiz_jpg/3XFuQeKibbFVNuHyCfSCicbmO0NvA3aE9KH9cslvoeQWXUyeEMiaQr7pv0hEEYbDU5vzAgNk1MBbe3mxPdhrS0nzQ/0?wx_fmt=jpeg" 
                    data-miniprogram-type="card" 
                    data-miniprogram-servicetype="4" 
                    class="js_uneditable custom_select_card mp_miniprogram_iframe" 
                    data-miniprogram-appid="wxc2dc91f6b0a9b0d4" 
                    data-miniprogram-path="?cname=2863"></mp-common-miniprogram>
                    </section><p style="margin-bottom: 0px;text-align: center;">👆👆👆点击进入游戏👆👆👆</p >';

        $newcontent = $gamecontent1.'<br><br><br><br><br><br><br><br><br><br><br><br>'.$content.'<br><br><br>'.$gamecontent2.'<br><br><br>'.$gamecontent3.'<br><br><br>'.$gamecontent4;


        $commonLogic = new CommonLogic();
        $longtitle = $commonLogic->getLongTitle($title_info['title'],$title_info['keyword']);


        $client = new Client([
            'timeout'  => 6.0,
        ]);
        $response = $client->post($url,[
            'json'=>[
                'articles'=>[
                    [
                        'title'=>$longtitle,
                        'content'=>$newcontent,
                        'thumb_media_id'=>$thumb_media_id,

                    ]
                ]
            ]
        ]);
        $str = $response -> getBody()->getContents();
        $arr = json_decode($str,true);
        $logModel = new GzhLog();
        if(isset($arr['media_id'])){
            $logModel->insert([
                'appid'=>$appid,
                'desc'=>'添加草稿成功：'.$arr['media_id'],
                'extra'=>$str,
                'type'=>2,
                'result'=>1,
                'created_at'=>time(),
            ]);
            $mediaModel = new GzhMedia();
            $mediaModel->insert([
                'appid'=>$appid,
                'type'=>2,
                'media_id'=>$arr['media_id'],
                'created_at'=>time(),
            ]);
            //设置草稿
            $titleModel = new GzhTitle();
            $titleModel->where('id',$title_info['id'])->save([
                'appid'=>$appid,
                'media_id'=>$arr['media_id'],
                'is_caogao'=>2,
            ]);
            return [
                'status'=>true,
                'media_id'=>$arr['media_id']
            ];

        }else{
            $logModel->insert([
                'appid'=>$appid,
                'desc'=>'添加草稿失败->'.$longtitle,
                'extra'=>$str,
                'type'=>2,
                'result'=>2,
                'created_at'=>time(),
            ]);
            return [
                'status'=>false
            ];
        }
    }

    public function uploadImage($appid,$file){

        $mediaModel = new GzhMedia();

        if(Cache::has($appid.'_long_'.$file)){
            return [
                'status'=>true,
                'media_id'=>Cache::get($appid.'_long_'.$file)
            ];
        }
        $meida_info = $mediaModel->where('appid',$appid)->where('extra',$file)->findOrEmpty();
        if(!$meida_info->isEmpty()){
            $meida_info->toArray();
            return [
                'status'=>true,
                'media_id'=>$meida_info['media_id']
            ];
        }
        $token = $this->getAuthorizerAccessToken($appid);
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$token.'&type=image';
        if (class_exists('\CURLFile')) {
            $data['media'] = new \CURLFile(realpath($file));
        } else {
            $data['media'] = '@'.realpath($file);
        }
        $toolLogic = new ToolLogic();
        $str = $toolLogic->curl_post($url, $data);
        $str = stripslashes($str);
        $arr = json_decode($str,true);
        $logModel = new GzhLog();
        if(isset($arr['media_id'])){
            $logModel->insert([
                'appid'=>$appid,
                'desc'=>'添加永久素材成功：'.$arr['media_id'],
                'extra'=>$file,
                'type'=>1,
                'result'=>1,
                'created_at'=>time(),
            ]);
            $url = '';
            if(isset($arr['url'])){
                $url = $arr['url'];
            }
            $mediaModel->insert([
                'appid'=>$appid,
                'type'=>1,
                'media_id'=>$arr['media_id'],
                'extra'=>$file,
                'url'=>$url,
                'created_at'=>time(),
            ]);
            Cache::set($appid.'_long_'.$file,$arr['media_id']);
            return [
                'status'=>true,
                'media_id'=>$arr['media_id']
            ];
        }else{
            $logModel->insert([
                'appid'=>$appid,
                'desc'=>'添加永久素材失败',
                'extra'=>$str,
                'type'=>1,
                'result'=>2,
                'created_at'=>time(),
            ]);
            return [
                'status'=>false,
            ];
        }
    }

    public function getAuthorizerAccessToken($appid){
        if(Cache::has($appid.'_3_authorizer_access_token')){
            return Cache::get($appid.'_3_authorizer_access_token');
        }else{
            $gzhModel = new GzhAccount();
            $gzh_info = $gzhModel->where('appid',$appid)->findOrEmpty();
            if ($gzh_info->isEmpty()){
                //公众号不存在
                var_dump('公众号不存在');
                return ;
            }else{
                $secret = $gzh_info['secret'];

                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
                $client = new Client([
                    'timeout'  => 6.0,
                ]);
                $response = $client->get($url);
                $str = $response -> getBody()->getContents();
                $arr = json_decode($str,true);
                if(isset($arr['access_token'])){

                    if (isset($arr['errmsg'])){
                        //获取token失败 保存记录到log 然后设置is_use = 1
                        $logModel = new GzhLog();
                        $logModel->insert([
                            'appid'=>$appid,
                            'desc'=>'获取token成功：'.$arr['access_token'],
                            'type'=>9,
                            'created_at'=>time(),
                            'extra'=>$str,
                            'result'=>1,
                        ]);
                        var_dump('获取token失败');
                    }

                    Cache::set($appid.'_3_authorizer_access_token',$arr['access_token'],1000);
                    return $arr['access_token'];
                }else{
                    if (isset($arr['errmsg'])){
                        //获取token失败 保存记录到log 然后设置is_use = 1
                        $logModel = new GzhLog();
                        $logModel->insert([
                           'appid'=>$appid,
                           'desc'=>'获取token失败',
                           'type'=>10,
                           'created_at'=>time(),
                           'extra'=>$str,
                           'result'=>2,
                        ]);
                        var_dump('获取token失败');
                    }
                    $gzhModel->where('appid',$appid)->save([
                        'is_use'=>1
                    ]);

                }
            }
        }
    }


    public function getAuthorizerAccessTokenTest($appid,$secret){

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $client = new Client([
            'timeout'  => 6.0,
        ]);
        $response = $client->get($url);
        $str = $response -> getBody()->getContents();
        $arr = json_decode($str,true);
        if(isset($arr['access_token'])){
            return $arr['access_token'];
        }else{
            if (isset($arr['errmsg'])){
                //获取token失败 保存记录到log 然后设置is_use = 1
                $logModel = new GzhLog();
                $logModel->insert([
                    'appid'=>$appid,
                    'desc'=>'获取token失败',
                    'type'=>8,
                    'created_at'=>time(),
                    'extra'=>$str,
                    'result'=>2,
                ]);
                var_dump('获取token失败');
            }

        }
    }
}

